package com.dtkavin.threads;

/**
 * Created by john on 10/3/16.
 * 目前实现了多线程。1,2没有实现互斥和同步,3 and 4 实现了互斥，但没有实现同步
 * this的互斥锁是实例对象，static 中的互斥锁是字节码对象
 */
public class SynchronizedDemo {

    class Share {
        public void print(String name) {
            System.out.println(name);
        }
    }

    private Share share = new Share();

    public void threadRun1(final String name) {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    share.print(name);
                }
            }
        }).start();

    }

    public void threadRun2(final String name) {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    share.print(name);
                }
            }
        }).start();

    }

    public void threadRun3(final String name) {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    selfPrint(share,name);
                }
            }
            public synchronized void selfPrint(Share share,String name){
                share.print(name);
            }
        }).start();

    }

    public void threadRun4(final String name) {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (this) {
                        share.print(name);
                    }
                }
            }
        }).start();

    }
}
